﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using AutoMapper;

namespace DAO
{
    public class TheLoaiRepository
    {
        public static THE_LOAI CreateTheLoaiEFFromTheLoaiDTO(TheLoaiDTO theLoaiDTO)
        {
            THE_LOAI theLoaiEF = new THE_LOAI();
            Mapper.CreateMap<TheLoaiDTO, THE_LOAI>();
            theLoaiEF = Mapper.Map<TheLoaiDTO, THE_LOAI>(theLoaiDTO);
            return theLoaiEF;
        }

        public static TheLoaiDTO CreateTheLoaiDTOFromTheLoaiEF(THE_LOAI theLoaiEF)
        {
            TheLoaiDTO theLoaiDTO = new TheLoaiDTO();
            Mapper.CreateMap<THE_LOAI, TheLoaiDTO>();
            theLoaiDTO = Mapper.Map<THE_LOAI, TheLoaiDTO>(theLoaiEF);
            return theLoaiDTO;
        }

        public List<TheLoaiDTO> LayDanhSachTheLoai()
        {
            List<TheLoaiDTO> ListTheLoai = new List<TheLoaiDTO>();
            try
            {
                QLTVEntities context = ContextFactory.GetInstance();
                var query = from theLoai in context.THE_LOAIList
                            select theLoai;               
                foreach (var theLoaiEF in query)
                {
                    TheLoaiDTO theLoaiDTO = CreateTheLoaiDTOFromTheLoaiEF(theLoaiEF);                    
                    ListTheLoai.Add(theLoaiDTO);
                }
            }
            catch (System.Exception)
            {
            }
            return ListTheLoai;     
        }

        public void ThemTheLoai(TheLoaiDTO theloaiDTO)
        {
            try
            {
                QLTVEntities contex = ContextFactory.GetInstance();
                THE_LOAI theloaiEF = new THE_LOAI();
                theloaiEF.TenTheLoai = theloaiDTO.TenTheLoai;
                contex.AddToTHE_LOAIList(theloaiEF);
                contex.SaveChanges();
            }
            catch (System.Exception)
            {
            }
        }

        public TheLoaiDTO LayThongTinTheLoai(int maTheLoai)
        {
            TheLoaiDTO theloaiDTO = new TheLoaiDTO();
            try
            {
                QLTVEntities context = ContextFactory.GetInstance();
                var query = from theloai in context.THE_LOAIList
                            where theloai.MaTheLoai == maTheLoai
                            select theloai;
                THE_LOAI theloaiTemp = query.First();
                if (theloaiTemp != null)
                {
                    theloaiDTO = CreateTheLoaiDTOFromTheLoaiEF(theloaiTemp);
                }
            }
            catch (System.Exception)
            {

            }
            return theloaiDTO;
        }
    }
}
